const time_transform = require("../../util/time_transform.js")
var app = getApp()
var baseUrl = app.globalData.baseUrl
var goods_id
Page({
  data: {
    goodsInfo: null,
    publisher: [],
    auctionRecord: null,
    clock: '',
    changePrice: 0, //出价
    priceValue: ''
  },

  onLoad(options) {
    let goodsId = options.goodsid
    //将id存起来给onshow用
    goods_id = goodsId
    //获取商品信息
    this.getGoodsInfo(goodsId)
    //倒计时
    this.countdown(goodsId)
  },
  onPullDownRefresh() {
    wx.showLoading({
      title: '刷新中',
    })
    setTimeout(() => {
      this.getGoodsInfo(goods_id)
    }, 500)
    setTimeout(() => {
      wx.hideLoading({
        success: (res) => {},
      })
    }, 1000)
  },
  onShow() {
    this.getGoodsInfo(goods_id)
    this.getAuctionRecord()
  },

  //根据商品id查询商品
  getGoodsInfo(goodsId) {
    wx.request({
      url: baseUrl+'goods/getGood/'+goodsId,
      method: 'POST',
      success: res => {
        this.setData({
          goodsInfo: res.data,
          changePrice: res.data.current_price + 1
        })
        //获取发布者信息
        wx.request({
          url: baseUrl+'user/getUserById/'+res.data.publisher_id,
          method: 'GET',
          success: res => {
            console.log('发布者',res)
            this.setData({
              publisher: res.data
            })
          }
        })
      }
    })
  
  },
  //底部加减价格
  addPrice() {
    var price = this.data.changePrice
    price++
    this.setData({
      changePrice: price,
      priceValue: ''
    })
  },
  downPrice() {
    var price = this.data.changePrice
    if (price > this.data.goodsInfo.current_price + 1) {
      price--
      this.setData({
        changePrice: price,
        priceValue: ''
      })
    } else {
      wx.showToast({
        title: '出价应当高于当前价！',
        icon: 'none'
      })
    }
  },
  setPrice(e) {
    let price = e.detail.value
    console.log(price)
    this.setData({
      changePrice: price * 1,
      priceValue: price * 1
    })
  },
  addPrice10() {
    console.log(this.data.changePrice)
    this.setData({
      changePrice: this.data.changePrice * 1 + 10,
      priceValue: ''
    })
  },
  addPrice100() {
    this.setData({
      changePrice: this.data.changePrice * 1 + 100,
      priceValue: ''
    })
  },

  //竞拍者出价
  putPrice() {
    //获取出价
    let price = this.data.changePrice
    //获取出价用户
    let userInfo = wx.getStorageSync('userInfo')
    //获取出价时间
    let nowTime = new Date().getTime()
    //转化为时间格式
    var util = require("../../util/time_transform.js")
    let timeFormat = util.js_date_time(nowTime)
    //弹窗确认
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'error'
      })
      this.login()
    } else {
        //判断自己是否是发布者
        //获取出价用户
        let userInfo = wx.getStorageSync('userInfo')
        if (this.data.goodsInfo._openid == userInfo._openid) {
          wx.showToast({
            title: '这是你发布的物品哦',
            icon: 'none'
          })
        } else {
          if (price < this.data.goodsInfo.current_price + 1) {
            wx.showToast({
              title: '必须高于当前价',
              icon: 'error'
            })
          } else {
            //查询商品状态
            wx.request({
              url: baseUrl+'goods/getStatus/'+goods_id,
              method: 'POST',
              success: res => {
                console.log(res.data)
                if(res.data === 1){
                  wx.showToast({
                    title: '竞拍还未开始！',
                    icon: 'error'
                  })
                  return 
                }else if( res.data ===3){
                  wx.showToast({
                    title: '竞拍已结束',
                    icon:'error'
                  })
                  return 
                }
                else{
                  wx.showModal({
                    title: '确认出价',
                    content: '价高者得，竞拍结束价高者可在竞拍记录中查看卖家联系信息，感谢您的参与！',
                    success: (res) => {
                      if (res.confirm) {
                        wx.showLoading({
                          title: '正在出价...',
                        })
                        let auctionRecord = {
                          goodsID: goods_id,
                          userInfo: userInfo,
                          putPrice: price,
                          auctionTime: nowTime,
                          auctionTimeFormat: timeFormat
                        }
                        //保存竞拍记录到数据库
                        wx.request({
                          url: baseUrl+'goodsAuctionRecord/set',
                          method:'POST',
                          data: auctionRecord,
                          success: res => {
                            console.log(res)
                          }
                        })
                          //更新当前价
                        wx.request({
                          url: baseUrl+'goods/updatePrice/'+goods_id+'/'+price,
                          method: 'POST',
                          success: res => {
                            console.log('更新',res)
                          }
                        })
                        let _this = this
                        setTimeout(function () {
                          //刷新页面数据
                          _this.onShow()
                          wx.hideLoading({
                            success: (res) => {
                              wx.showToast({
                                title: '出价成功',
                              })
                            }
                          })
                        }, 1000)
                      } else {}
                    }
                  })
                }
              }
            }) 
          }
        }
      } 
    },
  //获取商品用户竞拍记录
  getAuctionRecord() {
    wx.request({
      url: baseUrl+'goodsAuctionRecord/get/'+goods_id,
      method:'GET',
      success: (res) => {
        this.setData({
          auctionRecord: res.data
        })
        console.log('出价记录',res.data)
      }
    })
  },

  //获取竞拍结束时间，并计算倒计时
  countdown(goodsId) {
    wx.cloud.database().collection('goods').doc(goodsId).get({
      success: res => {
        //取出竞拍结束时间，精确到秒
        let auctionEndtime = this.data.goodsInfo.end_time
        //获取当前系统时间,只精确到秒
        var nowTime = new Date().getTime() / 1000
        //剩余时间总的秒数
        var totalSecond = Math.floor(auctionEndtime - nowTime)
        //计算倒计时
        this.doCountdown(totalSecond)
      }
    })
  },

  //计算商品倒计时
  doCountdown(totalSecond) {
    let _this = this
    //每隔一秒执行一次代码
    if (totalSecond > 0) {
      var myTime = setInterval(() => {
        //如果竞拍已经结束
        if (totalSecond < 0) {
          _this.setData({
            clock: '已经截止'
          })
          clearInterval(myTime)
          return
        } else {
          //执行计算
          var time = _this.formatTime(totalSecond)
          _this.setData({
            clock: '剩余' + time
          })
        }
        totalSecond--;
      }, 1000)
    } else {
      this.setData({
        clock: '已经截止'
      })
    }
  },

  //倒计时时间格式化
  formatTime(totalSecond) {
    //剩余天数
    var day = Math.floor(totalSecond / 3600 / 24)
    //n天后剩余小时数
    var hour = Math.floor(totalSecond / 3600 % 24)
    //n天n小时后剩余分钟数
    var min = Math.floor(totalSecond / 60 % 60)
    //n天n小时n分钟后剩余秒数
    var sec = Math.floor(totalSecond % 60)
    return day + "天" + hour + "小时" + min + "分" + sec + "秒"
  },
  //预览商品图片
  previewImg(e) {
    let index = e.currentTarget.dataset.index
    let imagesUrl = this.data.goodsInfo.images
    wx.previewImage({
      urls: imagesUrl,
      current: imagesUrl[index]
    })
  },
  //未登录用户要先登录
  getOpenid() {
    wx.cloud.callFunction({
      name: 'get',
      complete: res => {
        let openid = res.result.openid;
        this.setData({
          openid: openid
        })
      }
    })
  },

  login() {
    this.getOpenid()
    wx.getUserProfile({
      desc: '获取用户信息',
      success: res => {
        var user = res.userInfo
        let user_openid = this.data.openid
        //设置局部用户信息
        this.setData({
          userInfo: user,
          hasUser: true
        })
        //检查数据库是否有该用户
        wx.request({
          url: baseUrl+'user/getUserInfo/'+user_openid,
          method:'GET',
          success: res => {
            console.log(res)
            //原先没有添加，这里添加
            if (!res.data) {
              //将数据添加到数据库
              wx.request({
                url: baseUrl+'user/addUser',
                method: 'POST',
                data: {
                  avatarUrl: user.avatarUrl,
                  nickName: user.nickName,
                  _openid: user_openid
                },
                success: res => {
                  console.log(增加的用户)
                  if(res.data){
                    wx.setStorageSync('userInfo',res.data)
                  }
                }
            }) 
          }else{
            wx.setStorageSync('userInfo', res.data)
          }
        }
    })
    }
  })
  },
})